<template>
  <div class="page">
    <div class="main">
      <div v-for="(item, key) in components">
        key:{{ key }}
        <component :is="item"></component>
      </div>
    </div>
  </div>
</template>
<script setup>
import { defineAsyncComponent, ref, onMounted } from 'vue'
import * as Vue from 'vue'

import { loadModule } from 'vue3-sfc-loader'

import axios from 'axios'

import Overview from './components/Overview.vue'
import BarChart from './components/BarChart.vue'
import PieChart from './components/PieChart.vue'
import List from './components/List.vue'
import Tag from './components/Tag.vue'
import Info from './components/Info.vue'

// const Header = loadRemoteComponent('/remote-component/Header.vue')
// const Chatjs = loadRemoteComponent('/remote-component/Chatjs.vue')

const components = reactive({})

onMounted(() => {
  axios.get('/components.json').then(res => {
    res.data.forEach(async (filename, index) => {
      const name = filename.split('.')[0]
      components[name] = loadRemoteComponent(`/remote-component/${filename}`)
    })

    // res.data.forEach(async (item, index) => {
    //   const name = item.filename.split('.')[0]

    //   components[name] = loadRemoteComponent(`/remote-component/${item.filename}`)
    // })
  })
})

function loadRemoteComponent(url) {
  return defineAsyncComponent(async () => {
    const res = await loadModule(url, {
      moduleCache: {
        vue: Vue,
      },
      async getFile(url) {
        const res = await fetch(url)
        const code = await res.text()
        return code
      },
      addStyle(textContent) {
        const style = Object.assign(document.createElement('style'), {
          textContent,
        })
        const ref = document.head.getElementsByTagName('style')[0] || null
        document.head.insertBefore(style, ref)
      },
    })
    return res
  })
}
</script>
<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f2f4f8;
}

.main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  display: grid;
  gap: 24px;
  // grid-template-columns: repeat(3, 1fr);
  // grid-template-columns: repeat(auto-fit, minmax(min-content, max-content));
  // grid-template-columns: repeat(auto-fill, minmax(33.3%, 1fr));
  // grid-template-columns: repeat(auto-fill, minmax(33.3%, 1fr));
}
</style>
